package com.eight.paper.admin.util;

import com.google.common.io.Files;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;

@Slf4j
public class FileUtil {
    public static void downloadFile(String path, String name, HttpServletResponse response) throws Exception {
        File file = new File(path);
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        String fileName = URLEncoder.encode(name, "utf-8");
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + file.length());
        response.setContentType("application/octet-stream;charset=utf-8");
        Files.copy(file, outputStream);
        outputStream.flush();
    }

    public static void deleteFile(String filePath) {
        File file = new File(filePath);
        if (!file.delete()) {
            log.error("Delete file {} error", filePath);
        }
    }

    public static boolean deleteAllFile(String dir) {
        File dirFile = new File(dir);
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            return false;
        }
        boolean flag = true;
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                deleteFile(files[i].getAbsolutePath());
            }else if (files[i].isDirectory()) {
                deleteAllFile(files[i].getAbsolutePath());
            }
        }
        if (!flag) {
            return false;
        }
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }
}
